package csv;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class CSVWriter extends FileWriter
{
  private int amountOfColumns;

  public CSVWriter(File location, String[] columnNames)
    throws IOException
  {
    super(location, false);
    this.amountOfColumns = columnNames.length;

    String newLine = "";
    for (int i = 0; i < this.amountOfColumns - 1; i++)
      newLine = newLine + "\"" + columnNames[i] + "\",";
    newLine = newLine + "\"" + columnNames[(this.amountOfColumns - 1)] + "\"";
    super.write(newLine);
  }

  public CSVWriter(File location)
    throws IOException
  {
    super(location, true);
    this.amountOfColumns = new CSVParser(location).getColumnNames().length;
  }

  public CSVWriter(CSVParser parser) throws IOException {
    super(parser.getLocation(), true);
    this.amountOfColumns = parser.getColumnNames().length;
  }

  public void writeToFile(String[] input) throws IOException {
    if (input.length != this.amountOfColumns) {
      throw new IOException();
    }
    super.write(System.getProperty("line.separator"));
    String newLine = "";
    for (int i = 0; i < this.amountOfColumns - 1; i++)
      newLine = newLine + "\"" + input[i] + "\",";
    newLine = newLine + "\"" + input[(this.amountOfColumns - 1)] + "\"";
    super.write(newLine);
  }

  public void writeToFile(String input) throws IOException {
    if (this.amountOfColumns != 1) {
      throw new IOException();
    }
    super.write(System.getProperty("line.separator"));
    super.write("\"" + input + "\"");
  }
}